<template>
  <div>
    <el-card class="elCard">
      <el-form :inline="true" class="search-form" ref="searchFormRef" :model="searchParams">

        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="searchParams.roleName" class="search-form-content" placeholder="请输入角色名称"></el-input>
        </el-form-item>

        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="searchParams.roleKey" class="search-form-content" placeholder="请输入权限字符"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchParams.status" class="search-form-content" placeholder="角色状态">
            <el-option
                v-for="status in [{label:'正常',value:'1'},{label:'停用',value:'2'}]"
                :label="status.label"
                :key="status.value"
                :value="status.value"
            >

            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间" prop="selectDate">
          <el-date-picker
              v-model="searchParams.selectDate"
              style="width: 240px"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"

          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="elCard">
      <el-button type="primary" @click="handleRoleAdd">添加</el-button>
      <el-button type="danger" :disabled="selectRoleIdList.length<=0" @click="handleRoleDelete(selectRoleIdList)">
        批量删除
      </el-button>
      <el-table :data="roleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="roleKey" label="权限字符" align="center"></el-table-column>
        <el-table-column prop="roleSort" label="显示顺序" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch :active-value="!scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" @click="handleUpdateRole(scope.row.roleId)">修改</el-button>
            <el-button type="danger" @click="handleRoleDelete([scope.row.roleId])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="margin-top: 10px"
          v-model:current-page="searchParams.pageNum"
          v-model:page-size="searchParams.pageSize"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :page-sizes="[1,5,10]"
          :total="total"
          @size-change="fetchRoleList"
          @current-change="fetchRoleList"

      />
      <!--        @size-change="updateSize"-->
      <!--        @current-change="updatePage"-->
    </el-card>

    <el-dialog v-model="roleDialogShow" width="500px">
      <template #header>
        {{ roleParam.roleId ? "修改角色" : "添加角色"}}
      </template>
      <el-form label-width="80px" :model="roleParam">
        <el-form-item label="角色名称">
          <el-input v-model="roleParam.roleName" placeholder="请输入角色名称"/>
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="roleParam.roleKey" placeholder="请输入权限字符"/>
        </el-form-item>
        <el-form-item label="角色顺序">
          <el-input-number v-model="roleParam.roleSort" :min="1" :max="10"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleParam.status">
            <el-radio :value="'0'">正常</el-radio>
            <el-radio :value="'1'">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
              ref="menuTreeRef"
              node-key="id"
              :data="menuTreeData"
              show-checkbox
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="roleParam.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogShow = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ElCard,
  ElSelect,
  ElOption,
  ElForm,
  ElDatePicker,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElSwitch,
  ElDialog,
  ElInputNumber,
  ElRadioGroup,
  ElRadio,
  ElTree, ElButton, ElMessage
} from 'element-plus'
import {nextTick, onMounted, reactive, ref} from "vue"
import {getRoleList, addRole, updateRole, deleteBatchRole, getRole} from "@/api/role/role.js";
import {treeselect,roleMenuTreeselect} from "@/api/menu/menu.js";

let total = ref(0)

let searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roleName: null,
  roleKey: null,
  status: null,
  selectDate: []
})

onMounted(() => {
  fetchRoleList()
})

let roleList = ref([]);

let selectRoleIdList = ref([])
const handleSelectionChange = (selectRoleList) => {
  selectRoleIdList.value = selectRoleList.map(item => item.roleId)
}

const handleUpdateRole = async roleId => {

  let roleMenuTreeRes= await roleMenuTreeselect(roleId)
  if(roleMenuTreeRes.code!==200){
    return
  }

  getRole(roleId).then(resp => {
    if (resp.code === 200) {
      roleParam.value = resp.data
      menuTreeData=reactive(roleMenuTreeRes.menus)
      selectRoleIdList.value=roleMenuTreeRes.checkedKeys
      roleDialogShow.value=true
      nextTick(()=>{
        menuTreeRef.value.setCheckedKeys(roleMenuTreeRes.checkedKeys)
      })
    }
  })

}
const handleRoleDelete = (roleIdList) => {
  deleteBatchRole(roleIdList).then(resp => {
    if (resp.code === 200) {
      ElMessage.success("删除成功")
      fetchRoleList()
    }
  })
}
let fetchRoleList = () => {

  let paramsCopy = {...searchParams};
  let selectDate = paramsCopy.selectDate
  // 删除 selectDate 属性，确保不影响 searchParams
  delete paramsCopy.selectDate
  let [beginTime, endTime] = selectDate || []
  getRoleList(paramsCopy, beginTime, endTime).then(resp => {
    if (resp.code === 200) {
      total.value = resp.total
      roleList.value = resp.rows
    }
  })
}

let handleSearch = () => {
  fetchRoleList()
}

const searchFormRef = ref()
let reset = () => {
  console.log(searchFormRef, 7)
  searchFormRef.value.resetFields()
}

let roleDialogShow = ref(false)

let menuTreeData = reactive([])
const handleRoleAdd = async () => {
  let resp = await treeselect()
  if (resp.code === 200) {
    menuTreeData = reactive(resp.data)
    resetRoleParam()
    selectRoleIdList.value=[]
    roleDialogShow.value = true
  }
}

let roleParam = ref()
const resetRoleParam = () => {
  roleParam.value = {
    roleName: "",
    roleKey: "",
    roleSort: 0,
    status: "0",
    menuIds: [],
    remark: ""
  }
}


let menuTreeRef = ref()
const submitRoleForm = async () => {
  roleParam.value.menuIds = menuTreeRef.value.getCheckedKeys()

  let resp
  let message
  if (roleParam.value.roleId) {
    resp = await updateRole(roleParam.value)
    message = "修改成功"
  } else {
    resp = await addRole(roleParam.value)
    message = "新增成功"
  }
  if (resp.code === 200) {
    ElMessage.success(message)
    roleDialogShow.value = false
    fetchRoleList()
  }

}
</script>


<style scoped lang="scss">
.elCard {
  margin: 0 30px;
  margin-bottom: 10px;
}

.search-form {
  .search-form-content {
    width: 240px;
  }
}

</style>